<?php
namespace app\common\model;

use think\Model;

class News extends Model
{
    public function insert($data = array()){
        if (!is_array($data) || !$data) {
            return 0;
        }
        $data['create_time'] = time();
        $data['username'] = getLoginUsername();
        return $this->allowField(true)->save($data);
    }

    public function getNews($data) {
        $conditions = array();
        if (isset($data['title']) && $data['title']) {
            $conditions['title'] = array('like','%'.$data['title'].'%');
        }
        if (isset($data['catid']) && $data['catid']) {
            $conditions['catid'] = intval($data['catid']);
        }
        $conditions['status'] = $data['status'];
        return $this->where($conditions)
            ->order('listorder desc ,news_id desc')
            ->paginate(3);
    }

    public function find($id){
        $data = $this->where('news_id',$id)->find();
        return $data;
    }

    public function updateById($id, $data){
        if(!$id || !is_numeric($id)) {
            throw_exception('ID不合法');
        }
        if(!$data || !is_array($data)) {
            throw_exception('更新数据不合法');
        }
        return $this->allowField(true)->save($data,['news_id' => $id]);
    }

    public function updateStatusById($id, $status){
        if(!is_numeric($status)) {
            throw_exception('状态不能为非数字');
        }
        if(!$id || !is_numeric($id)) {
            throw_exception('ID不合法');
        }
        $data['status'] = $status;
        return $this->save($data,['news_id'=>$id]);
    }

    public function updateNewsLisorderById($id, $listorder){
        if(!$id || !is_numeric($id)) {
            throw_exceptions("ID不合法");
        }
        $data['listorder'] = intval($listorder);
        $ret = $this->save($data, ['news_id' => $id]);
        return $ret;
    }

    public function getNewsByNewsIdIn($newsIds){
        if(!is_array($newsIds)) {
            throw_exceptions("参数不合法");
        }
        $data = array (
          'news_id' => array('in', implode(',', $newsIds)),
        );

        return $this->where($data)->select();
    }
}